﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Threading;
using System.Net;
using System.Diagnostics;
using System.IO;

namespace ReverseGeocoding.Library
{
    public class ReverseGeocodingLibrary
    {
        private static ReverseGeocodingLibrary _Instance = null;

        private ReverseGeocodingLibrary()
        {
            Debug.WriteLine("ctor Culture Setup Ok");
            CultureInfo culture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }

        public static ReverseGeocodingLibrary Instance()
        {
            if (_Instance == null)
            {
                _Instance = new ReverseGeocodingLibrary();
            }

            return _Instance;
        }


        /// <summary>
        /// Traduce las coordenadas a las coordenadas de la calle más cercana, utilizando la API de Google Maps
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lang"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public string ReverseGeocode(double lat, double lang, int timeout = 30)
        {           
            string responseFromServer = String.Empty;

            try
            {
                WebRequest req = WebRequest.Create(@"http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat.ToString("F5")+ "," + lang.ToString("F5") + "&sensor=true");
                Debug.WriteLine("LatLng son: " + lat.ToString("F5") + "," + lang.ToString("F5"));
                req.Timeout = timeout * 1000;
                req.Method = "GET";


                //#region Sending Stage
                //using (Stream dataStream = req.GetRequestStream())
                //{
                //    dataStream.Write(new byte[] { }, 0, 0);
                //    dataStream.Close();
                //} 
                //#endregion
                #region Receiving Stage
                using (WebResponse response = req.GetResponse())
                {
                    Debug.WriteLine("HTTP-GET: Transaction Status -> " + ((HttpWebResponse)response).StatusDescription);

                    using (Stream dataStream = ((WebResponse)response).GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            responseFromServer = reader.ReadToEnd();

                            reader.Close();
                        }
                        dataStream.Close();
                    }

                    response.Close();
                }
                #endregion

                Debug.WriteLine("Recibido: " + responseFromServer);

                //TODO: Hacer la deserializacion acá

              
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Excepcion realizando ReversGeocode: " + ex.Message + " - SS:" + ex.StackTrace);
                throw ex;
            }

            return responseFromServer;
        }
    }
}
